
#include <iostream>
#include <csignal>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>

void notice(int signo)
{
    std::cout << "get a signal: " << signo << ", pid: " << getpid() << std::endl;
    while (true)
    {
        pid_t rid = waitpid(-1, nullptr, WNOHANG);
        if (rid > 0)
        {
            std::cout << "wait child success, rid: " << rid << std::endl;
        }
        else if (rid < 0)
        {
            std::cout << "wait child success done!" << std::endl;
            break;
        }
        else
        {
            std::cout << "wait child success done!" << std::endl;
            break;
        }
    }
}

void DoOtherThing()
{
    std::cout << "DoOtherThing~" << std::endl;
    sleep(1);
}

int main()
{
    signal(SIGCHLD, notice);

    for (int i = 0; i < 10; ++i)
    {
        pid_t pid = fork();
        if (pid == 0)
        {
            std::cout << "It is child process, pid: " << getpid() << std::endl;
            sleep(3);
            exit(1);
        }
    }

    while (true)
    {
        DoOtherThing();
    }

    return 0;
}
